/**
* @file        StringUtils
* @brief       
* @version     1.0.0
* @author      Changlin.Jing 
* @date        2023/1/29 8:57
* @copyright   Copyright  2022 Langge Software Co., Ltd. All rights reserved.
*/
#include <regex>
#include <iostream>
#include "ut_string.hpp"


BEGIN_SPACE_LANGE_VDR

char *StringUtils::rtrim(char *str) {
    if (str == NULL || *str == '\0')
    {
        return str;
    }

    int len = strlen(str);
    char* p = str + len - 1;
    while (p >= str && (isspace(*p) || *p =='\n'))
    {
        *p = '\0';
        --p;
    }
    return str;
}

std::vector<std::string> StringUtils::SplitString(const std::string &in, const std::string &delim) {
    try
    {
        std::regex re(delim);
        return std::vector<std::string>(
                std::sregex_token_iterator(in.begin(),in.end(),re,-1),
                std::sregex_token_iterator());
    }
    catch(const std::exception &e)
    {
        std::cerr<<e.what()<<'\n';
        return std::vector<std::string>();
    }
}

/**
 *
 * @param in
 * @param delim
 * @param res
 */
void StringUtils::SplitString(const std::string &in,const std::string &delim,std::vector<std::string>& res)
{
    std::size_t previous = 0;
    std::size_t current = in.find(delim);
    while (current != std::string::npos) {
        if (current > previous) {
            res.push_back(in.substr(previous, current - previous));
        }
        previous = current + 1;
        current = in.find(delim, previous);
    }
    if (previous != in.size()) {
        res.push_back(in.substr(previous));
    }
}

END_SPACE_LANGE_VDR